<?php
class DiplomaIndexsController   extends Zone_Action{
	
	public function Fields($default=NULL){
		$data = array(
			type => array(
				type 		=> 'INT',
				form_label => 'Loại công văn',			
			),
			subtype => array(
				type 		=> 'INT',
				form_label => 'Loại công văn',			
			),
			code=>array(
				type=>'TEXT',
				no_empty	=>true,
				form_label=>'Số hiệu công văn',
				default_value => NULL
			),
			date_send => array(
				type => 'DATE',
				no_empty =>true,
				fix_value	=> change_date_format, 
				form_label => 'Ngày gửi',
				default_value => NULL
			),
			date_enactment => array(
				type => 'DATE',
				no_empty =>true,
				fix_value	=> change_date_format, 
				form_label => 'Ngày phát hành',
				default_value => NULL
			),
			
			ogran_by =>array(
				type		=>"TEXT",
				no_empty	=>true,
				form_label	=>"Cơ quan ban hành",
				default_value => NULL
			),
			abstracts  => array(
				type 			=> 'TEXT',
				no_empty		=>true,
				form_label 		=>'Trích yếu',
				default_value => NULL
			),
			prior	=> array(
				type 			=> 'TEXT',
				form_label 		=> 'Mức độ ưu tiên',
				no_empty		=>true,
				default_value => NULL
			),
			desc	=> array(
				type 			=> 'TEXT',
				form_label 		=> 'Ghi chú',
				default_value => NULL
			),
			created_by_id =>array(
				type			=>'INT',
				form_label		=>'Người tạo',
				default_value	=>get_user_id()
			),
			date_updated =>array(
				type			=>'DATETIME',
				form_label		=>'Ngày cập nhật',
				default_value	=>mysql_date()
			),
			updated_by_id=>array(
				type			=>'INT',
				form_label		=>'Người cập nhật',
				default_value	=>get_user_id()
			)
		);
		if( is_array( $default ) ){
			foreach( $data as $k => $config ){
				if( $config['type'] != 'NONE' && isset( $default[$k] ) ){
					$data[$k]['default_value'] = $default[$k];
				}
			}
		}	
		return $data;	
	}
	
	public function initAction(){
		$this->set(array(
			type =>$this->Model->fetchAll("SELECT * FROM `diplomas_types`")
		));
	}
	
	public function indexAction(){
		if(!$this->hasRole("add_diploma")){
			return $this->setContent(error("Bạn không có quyền truy cập phân hệ công văn."));
		}
		$type=get('bl');
		$user_id = get_user_id();
		$vars = array();
		switch ($type) {
			case 'indate':
				$condition = " AND DAY(`a`.`date_send`)=DAY(NOW())";
				break;
			case 'inmonth':
				$condition = " AND MONTH(`a`.`date_send`)=MONTH(NOW())";
				break;
		}
		
		$WHERE = array();
		$order_by = " ORDER BY `a`.`ID` DESC";
		
		$current_page = max(getInt('p',1),1);		
		$range_page = max(10,(int)$this->getConfig('user.page',20));
		
		if( isset($_REQUEST['p'])){
			$vars['p'] = $current_page;
		}
		
		$limit = "LIMIT ".($current_page-1)*$range_page.",$range_page";
				
		$field_order = array('subtype','code','date_send','date_enactment','ogran_by','abstracts');
		foreach( $field_order as $f ){
			if( get('order_by') == $f ){
				$order_by = "ORDER BY $f ". ( get('order_type') == 'desc' ? 'desc' : 'asc');
				$vars['order_by'] = $f;
				if( get('order_type') == 'desc' ){
					$vars['order_by']='desc';
				}
				break;	
			}	
		}		
		$total = $this->Model->fetchOne("
			SELECT COUNT(*) 
			FROM `diplomas` as `a`
				LEFT JOIN `diplomas_users` as `b` ON `b`.`diploma_id`=`a`.`ID` AND `b`.`user_id`='$user_id'
			WHERE 	`a`.`is_draft`='no' 
					AND `a`.`type`='send'
					
			$condition  $order_by $limit
		");
		$posts = $this->Model->fetchAll("
			SELECT `a`.*,`b`.`title` as `subtype_title`
				FROM `diplomas` as `a` 
					LEFT JOIN `diplomas_types` as `b` 
						ON `a`.`subtype`=`b`.`ID`
					LEFT JOIN `diplomas_users` as `c` 
						ON `c`.`diploma_id`=`a`.`ID` AND `c`.`user_id`='$user_id'
				WHERE 	`a`.`type`='send' 
						AND `a`.`is_draft`='no' 
				$condition $order_by $limit
		");
		
		$a = $vars;
		unset($a['p']);
		
		$page = page_ajax('#Diploma/Indexs/Index?'.to_query_configs($a).'&p=', $total , $range_page, $current_page);	
			
		$this->set(array(
			user_id	=> get_user_id(),
			page	=> $page,
			total	=> $total,
			vars	=> $vars,
			post	=> $posts
		));
	}

	
	public function viewAction(){
		$id = getInt("ID",0);
		
		$post = $this->Model->fetchRow("
			SELECT `a`.*,`b`.`title` as `subtype`,`c`.`username` as `updated_by_name`,`c`.`is_deleted` as `updated_is_deleted`
				FROM `diplomas` as `a`
					LEFT JOIN `diplomas_types` as `b` ON `b`.`ID`=`a`.`subtype`
					LEFT JOIN `users` as `c` ON `a`.`updated_by_id`=`c`.`ID`
				WHERE `a`.`ID`='$id'
		");
		$file = $this->Model->fetchAll("
			SELECT * 
			FROM `diplomas_files` 
			WHERE `diploma_id`='$id'
		");
		$userView = $this->Model->fetchAll("
			SELECT `a`.*,`b`.*
			FROM `diplomas_users` as `a` 
				LEFT JOIN `users` as `b` ON `b`.`ID`=`a`.`user_id`
			WHERE `a`.`diploma_id`='$id'
		");
		$this->set(array(
			post 		=>	$post,
			files 		=>	$file,
			userView		=>$userView
		));
	}
	
	/* delete file or forder */
	public function deleteAction(){
		$id=getInt("ID",0);
		$user_id = get_user_id();
		
		$chk = $this->Model->fetchRow("SELECT * FROM `diplomas` WHERE `ID`='$id'");
		if($chk['created_by_id']!=$user_id){
			return $this->setJSON(array(
				alert => error("Bạn không có quyền xóa công văn này")
			));
		}
		$this->Model->delete("diplomas_files","`diploma_id`='$id'");
		$this->Model->delete("diplomas_users","`diploma_id`='$id'");
		$this->Model->delete("diplomas"," `ID`='$id' ");
		return $this->setJSON(array(
			redirect	=> "#Diploma"
		));
	}
	
	
	public function fileAction(){
		$file_id = get('ID',0);
		$user_id = get_user_id();
		$file = $this
			->Model->fetchRow("SELECT * FROM `diplomas_files` as `a` WHERE `a`.`ID`='$file_id' LIMIT 1");
		
		$file_path = "files/diploma/{$file['name']}";
		
		if( !file_exists( $file_path ) ){
			return $this->setError('404');
		}	
		if( get('type') == 'icon' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->resize(60, 60);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else if( get('type') == 'view' ){	
			$img_types = array('image/gif','image/png','image/x-png','image/jpeg','image/x-jpeg','image/jpg');
			if( in_array($file['type'],$img_types) ){
				loadClass('PHPThumb');
				$thumb = PhpThumbFactory::create($file_path);
				$thumb->show();
			}else{
				@readfile("files/static/icon.gif");	
			}		
		}else{
			@header("Content-Disposition: attachment; filename={$file['name']}");
			@readfile($file_path);
		}
	}
	
	
	public function addAction(){
		if(!$this->hasRole("add_diploma")){
			return $this->setContent(error("Bạn không có quyền tạo công văn"));
		}
		$user_id = get_user_id();
		$post = $this->Model->fetchRow("SELECT * FROM `diplomas` WHERE `created_by_id`='$user_id' AND `is_draft`='yes' AND `type`='send' LIMIT 1");
		
		if($post){
			$diploma_id = $post['ID'];
			$files = $this->Model->fetchAll("SELECT * FROM `diplomas_files` WHERE `diploma_id`='$diploma_id'");
		}else{
			$this->Model->insert("diplomas",array(
				is_draft		=> 'yes',
				type			=>'send',
				created_by_id	=> $user_id			
			));
			$post 	 = array();
			$files   = array();
			$diploma_id = $this->Model->lastId();
		}
		
		$this->set(array(
			post				=> 	$post,
			diploma_id 			=>	$diploma_id,
			files				=> 	$files,
			users				=>	$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'")
		));
		if(isPost()){
			
			$diploma_id = $_POST['diploma_id'];
			loadClass("ZData");
			$form = new ZData();
			$form->addFields( $this->Fields($post));
			$data = $form->getData();
			
			if( is_array($data)){
				if($post["date_created"]==null){
					$data['created_by_id'] = get_user_id();
					$data['date_created']  = date("Y-m-d H:i:s");
				}
				
				$data['is_draft']='no';
				$this->Model->update("diplomas",$data," `ID`='$diploma_id'");
				
				////////////////////////////////
				$roles = array();				
				$usersGet = (array)$_POST['usersGet'];				
				foreach( $usersGet as $k => $uid ){
					if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
						continue;
					}	
					$roles[$uid] = array(
						diploma_id	 => $diploma_id,
						user_id		 => $uid,
						is_proc 	 => 'NULL',
						is_decide 	 => 'NULL'
					);	
				}	
				
				foreach( $roles as $role ){
					$this->Model->insert('diplomas_users',$role);
					$this->Model->insert('notices',array(
						created_by_id	=> $user_id,
						user_id			=> $role['user_id'],
						url				=> "#Diploma/Indexs/View?ID=$diploma_id",
						title			=> $data['abstracts'],
						date			=> mysql_date(),
						content			=> "Bạn vừa nhận được một công văn mới."
					));				
				}
				///////////////////////////////
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `diplomas_files` WHERE `diploma_id`='$diploma_id'");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("diplomas_files","`ID`='{$f['ID']}'");
						@unlink("files/diploma/{$f['name']}");
					}
				}
				
				return $this->setJSON(array(
					redirect	=> "#Diploma/Indexs"
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}			
		}
	}
	public function editAction(){
		$user_id = get_user_id();
		$diploma_id = getInt('ID',0);
		$post = $this->Model->fetchRow("
			SELECT `a`.* FROM `diplomas` as `a` 
			WHERE `a`.`ID`='$diploma_id'");
			
		
		
		$files = $this->Model->fetchAll("SELECT * FROM `diplomas_files` where `diploma_id`='$diploma_id'");
		$usersGet = $this->Model->fetchAll("
			SELECT `a`.*,`b`.*
			FROM `diplomas_users` as `a` 
				LEFT JOIN `users` as `b` ON `b`.`ID`=`a`.`user_id`
			WHERE `a`.`diploma_id`='$diploma_id'
		");
		
		$this->set(array(
			post 				=> 	$post,
			diploma 			=>	$diploma_id,
			files				=> 	$files,
			users				=> 	$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$user_id'"),
			usersGet			=> 	$usersGet,
						
		));
		if(isPost()){
			loadClass("ZData");
			$diploma_id = $_POST["diploma_id"];
			
			$form = new ZData();
			$form->addFields( $this->Fields($post));
			$data = $form->getData();
			
			if( is_array($data)){
				if($post["date_created"]==null){
					$data['created_by_id'] = get_user_id();
					$data['date_created']  = date("Y-m-d H:i:s");
				}
				
				$data['is_draft']='no';
				$this->Model->update("diplomas",$data,"`ID`='$diploma_id'");
				
				////////////////////////////////
				$this->Model->delete("diplomas_users","`diploma_id`='$diploma_id'");
				$roles = array();				
				$usersGet = (array)$_POST['usersGet'];				
				foreach( $usersGet as $k => $uid ){
					if( !$this->Model->fetchRow("SELECT * FROM `users` WHERE `ID`='$uid' AND `is_deleted`='no'") ){
						continue;
					}	
					$roles[$uid] = array(
						diploma_id	 => $diploma_id,
						user_id		 => $uid,
						is_proc 	 => 'NULL',
						is_decide 	 => 'NULL'
					);	
				}	
				
				foreach( $roles as $role ){
					$this->Model->insert('diplomas_users',$role);
					$this->Model->insert('notices',array(
						created_by_id	=> $user_id,
						user_id			=> $role['user_id'],
						url				=> "#Diploma/Indexs/View?ID=$diploma_id",
						title			=> $data['abstracts'],
						date			=> mysql_date(),
						content			=> "Công văn mới được chỉnh sửa."
					));				
				}
				///////////////////////////////
				$files_selected = (array)$_POST['files'];
				$files = $this->Model->fetchAll("SELECT * FROM `diplomas_files` WHERE `diploma_id`='$diploma_id'");
				foreach( $files as $f ){
					if( !in_array( $f['ID'], $files_selected ) ){
						$this->Model->delete("diplomas_files","`ID`='{$f['ID']}'");
						@unlink("files/diploma/{$f['name']}");
					}
				}
				
				return $this->setJSON(array(
					redirect	=> "#Diploma/Indexs"
				));
			}else{
				return $this->setJSON(array(
					message => error($data)
				));
			}			
		}
	}
 	public function uploadAction(){
		$this->removeLayout();
		$diploma_id = getInt("ID",0);
			
		$user_id = get_user_id();
		if( isPost()){
			loadClass("ZData");
			$f = new ZData();
			$f->addField(array(
				file => array(
					type 		=> 'FILE',
					path		=> 'files/diploma/',
					no_empty	=> true
				)
			));
			
			$data = $f->getData();
			if( is_array( $data ) ){
				$file = $data['file'];
				
				$this->Model->insert("diplomas_files",array(
					diploma_id		=> $diploma_id,
					name			=> $file[0],
					type			=> $file[1],
					size			=> $file[2],
					filename		=> $file[3]
				));
				
				$file_id = $this->Model->lastId();				
				return $this->setJSON(array(
					content	=> "<div class='x-file-info'><input checked type='checkbox' name='files[]' value='$file_id'/>
								<a href='".ctrUrl($this)."/File?ID=$file_id' target='_blank'>{$file[3]} {$file[2]} KB	</a>
								</div>"
				));
			}else{
				return $this->setJSON(array(
					alert => error($data)
				));				
			}
			
		}	
	}
}
?>